package com.zds.passwordbox.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.zds.passwordbox.R;
import com.zds.passwordbox.adapter.CodeAccountAdapter;
import com.zds.passwordbox.common.Constant;
import com.zds.passwordbox.common.OnDialogDismissListener;
import com.zds.passwordbox.data.dao.AccountDao;
import com.zds.passwordbox.data.dao.domain.UserAccount;

import java.util.LinkedList;

public class CodeFragment extends Fragment implements OnDialogDismissListener {

    private Toolbar toolbar;

    private final AccountDao accountDao;

    private CodeAccountAdapter adapter;

    private CodeAccountAdd codeAccountAdd;

    private SmartRefreshLayout swipeRefreshLayout;

    private LinkedList<UserAccount> dataList = new LinkedList<>();

    public CodeFragment(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        toolbar = requireActivity().findViewById(R.id.my_toolbar);
        ((AppCompatActivity) requireActivity()).setSupportActionBar(toolbar);
        setHasOptionsMenu(true);
        View view = inflater.inflate(R.layout.code_fragment, container, false);
        initListView(requireContext(), view);
        this.codeAccountAdd = new CodeAccountAdd(accountDao);
        codeAccountAdd.setOnDialogDismissListener(this);
        swipeRefreshLayout = view.findViewById(R.id.account_list_refresh);
        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener((RefreshLayout refreshLayout) -> {
            refresh(null);
            // 停止刷新动画
            swipeRefreshLayout.finishRefresh();
        });
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void refresh(String qry) {
        if (adapter != null) {
            this.dataList.clear();
            this.dataList.addAll(accountDao.queryList(1, qry));
            adapter.notifyDataSetChanged();
        }
    }

    private void initListView(Context context, View view) {
        ListView listView = view.findViewById(R.id.account_list);
        // 获取账户列表
        this.dataList = accountDao.queryList(1, null);
        adapter = new CodeAccountAdapter(dataList, context);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view1, position, id) -> {
            if (!requireActivity().getSharedPreferences(Constant.USER_SETTING_NAME,
                    Context.MODE_PRIVATE).getBoolean(Constant.USER_KEY, false)) {
                new TipDialog("请先设置个人密钥").show(requireActivity().getSupportFragmentManager(), "tip");
                return;
            }
            new CodeDialog(accountDao, id).show(requireActivity().getSupportFragmentManager(), "code");
        });
        listView.setOnItemLongClickListener((parent, view2, position, id) -> {
            new AlertDialog.Builder(getActivity()).setTitle("是否删除此账户？")
                    .setPositiveButton("确定", (dialog, id1) -> {
                        accountDao.delete(id);
                        refresh(null);
                    })
                    .setNegativeButton("取消", ((dialog, which) -> dialog.dismiss()))
                    .show();
            return true;
        });
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        toolbar.setTitle(R.string.tab_code);
        //找到searchView
        inflater.inflate(R.menu.account_menus, menu);
        MenuItem item = menu.findItem(R.id.add_btn);
        if (item != null) {
            item.setOnMenuItemClickListener(item1 -> {
                if (!requireActivity().getSharedPreferences(Constant.USER_SETTING_NAME,
                        Context.MODE_PRIVATE).getBoolean(Constant.USER_KEY, false)) {
                    new TipDialog("请先设置个人密钥").show(requireActivity().getSupportFragmentManager(), "tip");
                    return true;
                }
                this.codeAccountAdd.show(requireActivity().getSupportFragmentManager(), "codeAccountAdd");
                return true;
            });
        }
        MenuItem searchItem = menu.findItem(R.id.account_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        if (searchView != null) {
            searchView.setQueryHint("请输入账户类型搜索");
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    // 根据输入的内容更新dataList
                    refresh(newText);
                    return true;
                }
            });
        }
    }

    @Override
    public void onDialogDismiss() {
        this.refresh(null);
    }
}
